import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { TOKEN_KEY, USERINFO_KEY } from '../config/prefix';

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(sessionStorage.getItem(`${TOKEN_KEY}`) || '');
  const userInfo = ref(
    JSON.parse(sessionStorage.getItem(`${USERINFO_KEY}`) || '{}')
  );

  // 计算属性
  const isLoggedIn = computed(() => Boolean(token.value));

  // 方法
  function setToken(newToken) {
    token.value = newToken;
    sessionStorage.setItem(`${TOKEN_KEY}`, newToken);
  }

  function setUserInfo(info) {
    userInfo.value = info;
    sessionStorage.setItem(`${USERINFO_KEY}`, JSON.stringify(info));
  }

  function logout() {
    token.value = '';
    userInfo.value = {};
    sessionStorage.clear();
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    setToken,
    setUserInfo,
    logout,
  };
});
